package com.centaline.androidsalesblog.rx.database;

import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.model.businissobject.DropBo;
import com.centaline.androidsalesblog.model.databaseobject.NewRegionDo;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;

/**
 * 获取新盘区域信息-下拉菜单
 * Created by guilin on 16/3/8.
 */
final class NewEstRegionDropOnSubscribe implements Observable.OnSubscribe<ArrayList<DropBo>> {

    @Override
    public void call(Subscriber<? super ArrayList<DropBo>> subscriber) {
        final ArrayList<DropBo> result = new ArrayList<>();
        final List<NewRegionDo> temp = DataSupport
                .where("cityCode = ? and GScopeLevel = ?", AppConstant.CityCode, "2")
                .find(NewRegionDo.class);
        DropBo dropBo1, dropBo2;
        if (temp != null &&
                temp.size() > 0) {
            for (NewRegionDo newRegionDo : temp) {
                dropBo1 = new DropBo(10);
                final List<NewRegionDo> temp2 = DataSupport
                        .where("cityCode = ? and ParentId = ?", AppConstant.CityCode, newRegionDo.getGScopeId())
                        .find(NewRegionDo.class);
                dropBo1.setValue(newRegionDo.getGScopeId());
                dropBo1.setText(newRegionDo.getGScopeCnName().trim());
                dropBo1.setChildrenList(new ArrayList<DropBo>());
                dropBo2 = new DropBo(10);
                dropBo2.setText(CommonConstant.DROP_TEXT_NO_LIMITED);
                dropBo2.setValue(CommonConstant.DROP_VALUE_NULL);
                dropBo1.getChildrenList().add(dropBo2);
                if (temp2 != null &&
                        temp2.size() > 0) {
                    for (NewRegionDo newRegionDo2 : temp2) {
                        dropBo2 = new DropBo(10);
                        dropBo2.setValue(newRegionDo2.getGScopeId());
                        dropBo2.setText(newRegionDo2.getGScopeCnName().trim());
                        dropBo1.getChildrenList().add(dropBo2);
                    }
                }
                result.add(dropBo1);
            }
        }
        if (!subscriber.isUnsubscribed()) {
            subscriber.onNext(result);
        }
        subscriber.onCompleted();
    }
}
